/**
 * @author xiaowei
 * @date 2017年4月25日
 */
Ext.define('App.view.common.CRUDTreeGrid', {
    extend: 'Ext.tree.Panel',
    mixins: ['App.view.common.CommonFun'],
    xtype: 'crudtreegrid',
    viewModel: {
        selectedView: false
    },
    queryMode:'local',//查询模式local本地过滤，remote远程请求过滤 当isShowSearchBar为true是，查询过滤默认采用本地过滤。
    _autoLoad: true,//自动请求数据
    openValidation: false,
    isCopyAdd: true,//当点击添加按钮时，是否启用复制新增功能。
    chineseName: '',//列表的中文名
    allowBlank: true,//用于做数据验证（是否允许列表中没有数据）。true是允许，false不允许。
    isShowSearchBar: false,//是否默认显示当前组件查询框
    searchMask:true,//查询数据是，是否出现mask遮罩层。 默认为true
    isOneLoad: false,//是否采用一次性加载树
    /*_mainConfs: [
     {name: 'name',type: 'string',text: '姓名'},
     {name: 'age',text: '年龄'},
     {name: 'email',type: 'string',text: '邮箱'},
     {name: 'date',type: 'date',text: '日期'}
     ],
     _validator: {name:{allowBlank:false},age:{minValue:0}},//数据验证器
     doNotValidEmpty: {name:true,age:true},//设置不需要验证的是否为空字段，该字段非空验证器将失效。
     */

    _confs: {//必要配置
        /*fields: [
         "name",
         'date',
         'age'
         ],
         url: '',//请求数据的url
         columns: ['name','date',{name:'age',width: 200}]*/
    },

    defaultParams:'',//{name: 12} 默认请求数据的参数，参数为对象
    columnsDefault: '',
    isAutoUrl: true,//如果没有配置url，自动生成一个url
    _isView: false,//是否是查看功能
    columnLines: true,
    rownumberer: true,//是否启用行号
    isRefreshRownum: true, //当编辑列表插入或删除数据时，是否刷新行号，默认刷新
    isPageGrid: true,//是否采用分页列表
    defaultDatas: '',//默认数据defaultDatas:[{name: 'zhangsan'},{name: 'lisi'}] 默认数据
    editColIndex: 1,//编辑列表时，新增数据默认光标激活索引号为1的单元格
    viewConfig: {
        enableTextSelection: true
    },
    autoScroll: true,
    rownumbererWidth:80,
    /*
     *配置参数
     */
    config: {
        isExport: false,
        exportFun: ''
    },
    initComponent: function () {
        if (this._isView || this.readOnly) {
            this.readOnly = this._isView = true;
        }
        if (!this.isLocked) {//修正由于锁列造成的二次初始化无法显示被锁列的缺陷
            this.initPhone();
            this._addValidator();
            this._setTools();
            this._setStore();
            this.columns = this._getColumns();
            this.showSearchBar();
        }
        if (this.readOnly) {
            this.selModel = 'rowmodel';
        }
        this.callParent();
    },
    initPhone:function () {
        if(!Ext.platformTags.desktop){
            this.rownumbererWidth = 40;
            if(this._confs && this._confs.columns){
                var components = this._confs.columns;
                for(var i = 0; i<components.length; i++){
                    components[i].minWidth = 120;
                }
            }

        }
    },
    _getFields: function () {
        if (!this._confs) {
            return;
        }
        var mcs = this._mainConfs,
            fs = this._confs.fields,
            fsRemove = this._confs.fieldsRemove,
            fsOverride = this._confs.fieldsOverride,
            temp, i, j, confObj, flag, type, field,
            fields = [];

        if (!fs && mcs) {//如果没有配置fields，那么自动根据_mainConfs生成fields
            for (i = 0; i < mcs.length; i++) {
                flag = true;
                type = mcs[i].type;
                if (!type) {
                    type = 'string';
                }

                if (fsRemove) {//判断是否配置需要移除的字段
                    for (j = 0; j < fsRemove.length; j++) {
                        if (mcs[i].name == fsRemove[j]) {
                            flag = false;
                        }
                    }
                }
                if (fsOverride && flag) {
                    for (j = 0; j < fsOverride.length; j++) {
                        confObj = fsOverride[j];
                        if (mcs[i].name == confObj.name) {
                            temp = this._getFieldByName(confObj.name);//该方法来自common.CommonFun对象
                            this._autoProperty(confObj, temp, ['name', 'type']);//自动生成
                            fields.push(confObj);
                            flag = false;
                        }
                    }
                }
                if (flag) {
                    field = {
                        name: mcs[i].name,
                        type: type
                    };

                    fields.push(field);

                }
            }
            return fields;
        } else if (fs) {//如果配置了fields，那么优先采用配置的fields

            for (i = 0; i < fs.length; i++) {
                confObj = fs[i];
                if (Ext.isString(confObj)) {//如果是字符串
                    temp = this._getFieldByName(confObj);//该方法来自common.CommonFun类
                    if (temp) {
                        type = temp.type;
                        if (!type) {
                            type = 'string';
                        }

                        field = {
                            name: temp.name,
                            type: type
                        };
                        fields.push(field);
                    } else {
                        fields.push(confObj);
                    }

                } else if (Ext.isObject(confObj)) {//如果是对象
                    temp = this._getFieldByName(confObj.name);//该方法来自common.CommonFun对象
                    this._autoProperty(confObj, temp, ['name', 'type']);//自动生成
                    fields.push(confObj);
                }
            }

        }
        return fields;
    },

    //将temp对象中的args字段复制到target对象中
    _autoProperty: function (target, temp, args) {

        if (!target.offAuto) {//是否自动生成开关，默认开启
            if (Ext.isString(args)) {
                if (!target.hasOwnProperty(args) && temp[args]) {
                    target[args] = temp[args];
                }
            }
            if (Ext.isArray(args)) {
                for (var i; i < args.length; i++) {
                    if (!target.hasOwnProperty(args[i]) && temp[args[i]]) {
                        target[args[i]] = temp[args[i]];
                    }
                }
            }
        }
    },

    _getColumns: function () {
        if (!this._confs) {
            return;
        }
        var mcs = this._mainConfs,
            cs = this._confs.columns,
            csRemove = this._confs.columnsRemove ? Ext.Array.clone(this._confs.columnsRemove) : [],
            csOverride = this._confs.columnsOverride,
            temp, i, j, confObj, dataIndexName,
            flag, align,
            columns = [];

        if (this.rownumberer) {
            columns = [{
                text: '序号',
                xtype: 'rownumberer',
                width: this.rownumbererWidth
            }];
        }
        var getFirstName = function (obj) {
            if (Ext.isString(obj)) {
                return obj;
            }
            if (obj.columns) {
                return getFirstName(obj.columns[0]);
            } else {
                return obj.dataIndex ? obj.dataIndex : obj.name;
            }
        };

        if (!cs && mcs) {//如果cs没有配置colums，那么自动根据_mainConfs生成columns
            for (i = 0; i < mcs.length; i++) {
                temp = mcs[i];
                flag = true;
                if (csRemove.length > 0) {//判断当前数据对象是否跳过生成列
                    flag = this._isRemain(csRemove, temp);
                }

                if (!flag) {
                    continue;
                }

                if (csOverride && flag) {//判断是否存在重写的列
                    csOverride = Ext.Array.clone(csOverride);
                    for (j = 0; j < csOverride.length; j++) {
                        confObj = csOverride[j];
                        if (getFirstName(confObj) == temp.name) {
                            this._getColumnByObject(confObj, csRemove);//列被重写后，把重写的名称加入csRemove中，避免重复生成列
                            columns.push(confObj);
                            Ext.Array.removeAt(csOverride, j);
                            flag = false;
                            break;
                        }
                    }
                }

                if (!flag) {
                    continue;
                }

                confObj = {flex: 1};
                this._autoColumnProperty(confObj, temp);
                columns.push(confObj);

            }
        } else if (cs) {//如果配置了columns，那么优先采用配置的columns

            for (i = 0; i < cs.length; i++) {
                confObj = cs[i];
                if (Ext.isString(confObj)) {//如果是字符串
                    columns.push(this._getColumnByString(confObj));
                } else if (Ext.isObject(confObj)) {//如果是对象
                    this._getColumnByObject(confObj);
                    columns.push(confObj);
                }
            }

        }
        return columns;
    },
    _isRemain: function (csRemove, obj) {
        var flag = true;
        for (var j = 0; j < csRemove.length; j++) {
            if (obj.name == csRemove[j]) {
                Ext.Array.removeAt(csRemove, j);
                flag = false;
                break;
            }
        }
        return flag;
    },
    _getColumnByString: function (confObj) {
        var column, temp;
        temp = this._getFieldByName(confObj);//该方法来自common.CommonFun类
        if (!temp) {
            alert('提示：dataMapping中没有找到字段名为[' + confObj + ']的映射对象！');
            return;
        }
        column = {};
        this._autoColumnProperty(column, temp);
        return column;
    },
    _getColumnByObject: function (confObj, csRemove) {
        var column, temp;

        if (confObj.columns) {//如果columns，证明配置是多列头。
            for (var i = 0; i < confObj.columns.length; i++) {
                if (Ext.isString(confObj.columns[i])) {//如果是字符串，转换成对象
                    confObj.columns[i] = this._getColumnByString(confObj.columns[i]);

                    if (Ext.isArray(csRemove)) {
                        csRemove.push(confObj.columns[i].dataIndex);
                    }

                } else if (Ext.isObject(confObj.columns[i])) {//如果是对象，继续递归
                    this._getColumnByObject(confObj.columns[i], csRemove);
                }
            }
        } else {//真正的column配置
            var dataIndexName = confObj.dataIndex ? confObj.dataIndex : false;
            if (!dataIndexName && confObj.name) {
                dataIndexName = confObj.name;
            }

            temp = this._getFieldByName(dataIndexName);//该方法来自common.CommonFun对象
            this._autoColumnProperty(confObj, temp);//自动添加默认属性

            if (Ext.isArray(csRemove)) {
                csRemove.push(dataIndexName);
            }

        }

    },

    _autoColumnProperty: function (target, temp) {
        if (this.columnsDefault) {
            Ext.applyIf(target, this.columnsDefault);
        }

        if (!target.offAuto && temp) {//是否自动生成开关，默认开启
            if (!target.hasOwnProperty('text') && temp.text) {
                target.text = temp.text;
            }
            if (!target.hasOwnProperty('dataIndex') && temp.name) {
                target.dataIndex = temp.name;
            }
            if (!target.hasOwnProperty('width')) {
                target.width = 100;
            }

            if (!target.hasOwnProperty('align') && temp.type) {
                target.align = 'left';
                if (temp.type == 'int' || temp.type == 'number' || temp.type == 'bigdecimal') {
                    target.align = 'right';
                } else if (temp.type == 'boolean') {
                    target.align = 'center';
                }
            }

            if (target.hyperlinkMode && !target.renderer) {//添加超链接效果
                target.renderer = function (val, metaData, record) {
                    if (!Ext.isEmpty(val)) {
                        return '<span style="color: blue;text-decoration:underline;cursor:pointer;">' + Ext.Component.htmlEscape(val) + '</span>';
                    }
                }
            }

            if (target.valueToName) {//是否将值转换为业务名称显示
                target.obj = Ext.create({
                    xtype: target.valueToName ? target.valueToName : target.dataIndex,
                    isInitChild: false
                });
                if (!target.renderer) {
                    target.renderer = function (val, metaData, record) {
                        return target.obj.valueToName(val, metaData, record);
                    }
                }
            }
            //当数据为bigdecimal、number、int类型，null值不返回数据
            if (temp.type == 'bigdecimal' || temp.type == 'number' || temp.type == 'int') {
                if (!target.renderer) {
                    target.renderer = function (val, metaData, record) {
                        if (val == 'null') {
                            return;
                        }
                        if (target.isPercent) {
                            if (!target.percentFormat) target.percentFormat = '0.00';
                            return Ext.util.Format.number(val * 100, target.percentFormat) + '%';
                        }
                        return val;
                    }
                }
            }
        }

    },

    setNullFlagQueryToParams:function (params) {
        var nullFlagQuery = true;
        if(!params){
            return {
                nullFlagQuery: nullFlagQuery
            };
        }
        for(var i in params){
            if(params[i] || params[i] === 0){
                nullFlagQuery = false;
                break;
            }
        }
        if(params && nullFlagQuery){
            params.nullFlagQuery = nullFlagQuery;
        }
        return params;
    },
    _search: function (params) {
        if (this.isOneLoad) {
            this._searchOneLoad(params);
            return;
        }
        var store
            , proxy
        ;

        store = this.getStore();

        if (params) {

            proxy = store.getProxy();
            proxy.extraParams = params;

        }

        if (this.isPageGrid) {
            store.loadPage(1);
        } else {
            store.load();
        }
    },

    /**
     * 设置store类名，如果参数为空，默认采用Ext.data.Store
     * @param className String 类名
     * @param configs Object 配置对象
     * @private
     */
    _setStore: function (className, configs) {
        var me = this,
            params = '',
            url = this._confs.url;
        if (!className) {
            className = 'Ext.data.TreeStore';
        }

        if (!url) {
            url = this.url;
        }
        if (!url && this.isAutoUrl) {
            url = this._getBaseUrl(this.ftgPanel) + '/pagingQuery';
        }

        if (this.defaultParams) {
            params = Ext.clone(this.defaultParams);
        }
        var baseConfig = {
            model: this._getModel(),
            filterer: 'bottomup',
            proxy: {
                type: 'ajax',
                url: url,
                extraParams: params,
                reader: {
                    type: 'json',
                    rootProperty: 'data'
                }
            },
            autoLoad: me._autoLoad
        };

        if (this.isOneLoad) {
            baseConfig.proxy = '';
            baseConfig.autoLoad = false;
            baseConfig.root = {text: 'root', children: []};
            if (me._autoLoad) {
                me.on({
                    afterrender: function () {
                        this._search(this.defaultParams);
                    }
                });
            }
        }


        if (configs) {
            Ext.applyIf(configs, baseConfig);
        } else {
            configs = baseConfig;
        }
        this.store = Ext.create(className, configs);

        if (this.defaultDatas) {
            this.store.setRoot(Ext.clone(this.defaultDatas));
        }
    },

    _setTools: function () {
        var me = this, i, temp;
        if (this.tools) {
            for (i = 0; i < this.tools.length; i++) {
                temp = this.tools[i];
                if (Ext.isString(temp)) {
                    if (temp == 'refresh') {
                        this.tools[i] = {
                            itemId: 'refresh',
                            type: 'refresh',
                            tooltip: '刷新',
                            callback: function (owner) {

                                owner._refresh();
                            }
                        };
                    }
                    if (temp == 'plus') {
                        this.tools[i] = {
                            type: 'plus',
                            tooltip: '添加数据（选中多行，可以进行复制添加）',
                            callback: function (owner) {
                                owner._addRecords();
                            }
                        };
                    }
                    if (temp == 'minus') {
                        this.tools[i] = {
                            type: 'minus',
                            tooltip: '删除数据',
                            callback: function (owner, recIndex, cellIndex, item, e, record) {
                                owner._removeRecords();
                            }
                        };
                    }
                }
            }
        }

    },

    _refresh: function () {
        var store
            , proxy
            , params = {}
        ;

        store = this.getStore();
        proxy = store.getProxy();
        if (this.defaultParams) {
            params = this.defaultParams;
        }
        if (this.isOneLoad) {
            this._searchOneLoad(params);
            return;
        }
        proxy.extraParams = params;
        store.load();

    },

    _addRecords: function () {
        var selections,
            me = this,
            selModel,
            currentNode,
            defaultData;
        selModel = this.getSelectionModel();
        selections = selModel.getSelection();
        defaultData = this.defaultDatas ? Ext.clone(this.defaultDatas) : {};

        if (selections.length < 1) {
            if(!this.store.getRoot()){
                this.store.setRoot({id:'root'});
            }
            currentNode = this.store.getRoot();
            defaultData.sortNum = 0;
            currentNode.insertChild(0, defaultData);
            currentNode.expand();
        } else {
            currentNode = selections[0];
            defaultData.sortNum = currentNode.get('index') + 1;
            currentNode.parentNode.insertChild(currentNode.get('index') + 1, defaultData);
            currentNode.parentNode.expand();
        }
        if(!Ext.isEmpty(this.editColIndex)){
            if(Ext.isEmpty(selModel.selectionStartIdx) || currentNode.id === 'root'){
                setTimeout(function () {
                    me.findPlugin('cellediting').startEditByPosition({row: 0, column: me.editColIndex});
                },10)
            }else{
                setTimeout(function () {
                    me.findPlugin('cellediting').startEditByPosition({row: me.getChildCount(currentNode) + selModel.selectionStartIdx + 1, column: me.editColIndex});
                },10)
            }
        }
        if (this.isRefreshRownum) {
            this.getView().refresh();
        }
    },
    getChildCount:function (record) {
        var count = 0;
        if(record.childNodes.length > 0){
            count = count + record.childNodes.length;
            for(var i in record.childNodes){
                count += this.getChildCount(record.childNodes[i]);
            }
        }
        return count;
    },
    _addChildRecords: function () {
        var selections,
            me = this,
            selModel,
            currentNode,
            defaultData;
        selModel = this.getSelectionModel();
        selections = selModel.getSelection();
        defaultData = this.defaultDatas ? Ext.clone(this.defaultDatas) : {};

        if (selections.length < 1) {
            currentNode = this.store.getRoot();
        } else {
            currentNode = selections[0];
        }
        defaultData.sortNum = currentNode.childNodes.length;
        currentNode.insertChild(currentNode.childNodes.length, defaultData);

        currentNode.expand();
        if (this.isRefreshRownum) {
            this.getView().refresh();
        }
        setTimeout(function () {
            me.findPlugin('cellediting').startEditByPosition({row: me.getChildCount(currentNode) + selModel.selectionStartIdx, column: me.editColIndex});
        },10)
    },

    _removeRecords: function () {
        var selections;

        selections = this.getSelectionModel().getSelection();
        if (!selections || selections.length < 1) {
            App.ux.Toast.show('提示', '请选中需要删除的行！','i');
            return;
        }
        selections[0].remove();
        if (this.isRefreshRownum) {
            this.getView().refresh();
        }
    },

    _getSelectionProcessInstanceIds: function () {
        var records = this.getSelection();
        var datas = [], record, i;
        for (i = 0; i < records.length; i++) {
            datas.push(records[i].get('processInstanceId'))
        }
        return datas;
    },

    //客户自定义验证逻辑，需要返回valid对象{valid: true, message: ''}
    _customValid: function () {
        var valid = {valid: true, message: ''};
        return valid;
    },
    /**
     * 逐条验证数据合法性
     * @param data
     * @param validator
     * @param record
     * @returns {{valid: boolean, message: string}}
     * @private
     */
    _validData: function (data, validator, record) {
        var valid = {
            valid: true,
            message: ''
        };

        for (var obj in validator) {
            if (validator[obj] && Ext.isEmpty(data[obj])) {//如果验证其中存在该字段，那么该字段将不允许为空值
                if (this.doNotValidEmpty && this.doNotValidEmpty[obj]) {//如果配置不需要验证的字段，跳过验证
                    continue;
                }
                valid.valid = false;
                valid.message += '【' + validator[obj].text.replace("<br>", "", "gi") + '】';
            }
        }
        if (!valid.valid) {
            valid.message += '不能为空</br>';
        }
        return valid;
    },
    //表格grid对自己列表数据进行验证，
    _gridValid: function (data) {
        if (!this.openValidation) {//如果验证器处于关闭状态，不做验证
            return {
                valid: true,
                message: 'openValidation属性为false，验证器处于关闭状态，跳过验证</br>'
            };
        }
        var store = this.getStore(),
            validator = this._createValidator(),
            valid = {valid: true, message: ''},
            me = this;
        if (!this.allowBlank && store.getCount() < 1) {
            valid.valid = false;
            valid.message = '列表不允许为空</br>';
            return valid;
        }

        if (!validator) {
            return valid;
        }

        if (data) {
            return this._validData(data, validator);
        }

        store.each(function (record, i) {
            var validResult, i = i + 1;
            validResult = me._validData(record.data, validator, record);
            if (!validResult.valid) {
                valid.valid = false;
                valid.message += '第' + i + '行:' + validResult.message;
            }

        });
        return valid;
    },
    isValid: function () {
        var form = this.down('form'),
            valid = true,
            message = this.chineseName + '<br>',
            customValid,
            gridValid;

        if (!this.openValidation) {//如果验证器处于关闭状态，不做验证
            return {
                valid: true,
                message: message + 'openValidation属性为false，验证器处于关闭状态，跳过验证<br>'
            };
        }
        if (form && !form.getForm().isValid()) {
            return {
                valid: false,
                message: message + '表单存在非法输入内容<br>'
            };
        }
        gridValid = this._gridValid();
        if (!gridValid.valid) {
            gridValid.message = message + gridValid.message;
            return gridValid;
        }
        //如果框架默认验证通过之后
        //执行用户自定义验证机制
        customValid = this._customValid();
        if (!customValid.valid) {
            valid = false;
            message += customValid.message;
        }

        return {
            valid: valid,
            message: message
        };
    },
    //返回value对象
    getValues: function () {
        var store = this.getStore();
        var values = [], value = {},me=this, formValues, temp;
        store.each(function (record, i) {
            temp = Ext.copy({}, record.data,me._BaseDataFields);
            if (temp.id && Ext.isString(temp.id) && temp.id.substring(0, 4) == "extM") {
                temp.id = '';
            }
            values.push(temp);

        });
        formValues = this.getFormValues();

        if (Ext.isEmpty(values) && Ext.isEmpty(formValues)) {
            return;
        }

        if (formValues) {
            value = Ext.apply(value, formValues);
        }

        if (this.name) {
            value[this.name] = values;
        } else {
            value[this.getId()] = values;
        }

        return value;
    },
    getFormValues: function () {
        var form = this.down('form');
        var values;
        if (form) {
            values = form.getForm().getValues();
        }
        return values;
    },

    getFormChangeValues: function (requires) {
        var form = this.down('form');
        var values;
        if (form) {
            values = form.getChangeValues(requires);
        }
        return values;
    },

    _getModel: function () {
        var fields = this._getFields();
        var model = Ext.create('Ext.data.TreeModel', {
            fields: fields,
            validators: this._createValidator()
        });
        return model;
    },

    _createValidator: function () {
        var mc = this._mainConfs, temp, validator = {};
        if (!mc) {
            return '';
        }
        if (this.validator) {
            return this.validator;
        }

        for (var i = 0; i < mc.length; i++) {
            temp = mc[i];
            if (temp.validator) {
                if (temp.validator.allowBlank === false) {
                    validator[temp.name] = {
                        text: temp.text
                    };
                }
            }
        }
        this.validator = validator;
        return validator;
    },

    showSearchBar: function () {
        var me = this;
        if (!this.isShowSearchBar) {
            return;
        }
        var searchBar = {
            xtype: 'textfield',
            //maxWidth: 300,
            name: 'searchField',
            dock: 'top',
            emptyText: '请输名称',

            triggers: {
                clear: {
                    cls: 'x-form-clear-trigger',
                    name:'clear',
                    handler: function (cmp) {
                        cmp.up('panel').onNavFilterClearTriggerClick(cmp);
                    },
                    hidden: true
                },
                search: {
                    cls: 'x-form-search-trigger',
                    weight: 1,
                    handler: function (cmp) {
                        cmp.up('panel').onNavFilterSearchTriggerClick();
                    }
                }
            },

            listeners: {
                change: function (field, newValue) {
                    field.up('panel').onNavFilterFieldChange(field, newValue);
                },
                buffer: 300,
                boxready:function () {
                    this.setWidth(me.getWidth());
                }
            }
        };
        if (this.dockedItems) {
            this.dockedItems.push(searchBar);
        } else {
            this.dockedItems = [searchBar];
        }

    },

    onNavFilterClearTriggerClick: function () {
        this.down('[name=searchField]').setValue();
        if(this.queryMode === 'remote'){//远程模式
            this._refresh();
        }
    },

    onNavFilterSearchTriggerClick: function () {
        var field = this.down('[name=searchField]');
        if(this.queryMode === 'remote'){//远程模式
            var param = {};
            if(this.defaultParams){
                param = Ext.clone(this.defaultParams);
            }
            param[this.filterName] = field.getValue();
            this._search(param);
            this.filterStore("");
            return;
        }
        this.onNavFilterFieldChange(field, field.getValue());
    },

    onNavFilterFieldChange: function (field, value) {
        var store = this.getStore(),
            selection = this.preFilterSelection;

        if (value) {
            this.preFilterSelection = this.getViewModel().get('selectedView');
            this.rendererRegExp = new RegExp('(' + value + ')', "gi");
            field.triggers.clear.show();
            this.filterStore(value);
        } else {
            this.rendererRegExp = null;
            store.clearFilter();
            field.triggers.clear.hide();

            // Ensure selection is still selected.
            // It may have been evicted by the filter
            if (selection && selection !== store.getRoot() && store.contains(selection)) {
                this.ensureVisible(selection, {
                    select: true
                });
            }
        }
    },

    filterStore: function (value) {
        var store = this.getStore();

        if (value.length < 1) {
            store.clearFilter();
        } else {
            store.getFilters().replaceAll({
                property: this.filterName,
                value: new RegExp(Ext.String.escapeRegex(value), 'i')
            });
            this.expandAll();
        }
    },

    treeNavNodeRenderer: function (value) {
        return this.rendererRegExp ? value.replace(this.rendererRegExp, '<span style="color:red;font-weight:bold">$1</span>') : value;
    },

    /**
     * 树节点一次性加载
     * @param params
     * @private
     */
    _searchOneLoad: function (params) {
        params = this.setNullFlagQueryToParams(params);
        var me = this,myMask;
        if(this.searchMask){
            myMask = new Ext.LoadMask({
                msg: '数据查询中...',
                target: me
            });
            myMask.show();
        }
        App.ux.Ajax.request({
            url: this.url,
            params: params,
            success: function (obj) {
                if(me.searchMask){
                    myMask.destroy();
                }

                me.getStore().convertCheckTree(obj.data);
                me.getStore().setRoot({
                    id:'root',
                    children:obj.data,
                    expanded:true
                });
                me.getStore().commitChanges();
            },
            failure: function () {
                if(me.searchMask){
                    myMask.destroy();
                }
            }
        });
    }


});